
import sqlalchemy
from sqlalchemy import create_engine, ForeignKey, Table, DATE
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import sessionmaker, relationship


Base = declarative_base() #生成orm基类

#不常用的创建表的方式,这张表一旦被创建我不会手动去管理他
book_m2m_author = Table('book_m2m_author', Base.metadata,
                        Column('book_id', Integer, ForeignKey('books.id')),
                        Column('author_id', Integer, ForeignKey('authors.id'))  #ForeignKey关联外键
                        )

class Book(Base):
    __tablename__ = 'books'
    id = Column(Integer, primary_key=True)
    name = Column(String(64))
    pub_date = Column(DATE)

    #这是关联三张表
    authors = relationship('Author', secondary=book_m2m_author, backref='books')

    def __repr__(self):
        return self.name

class Author(Base):
    __tablename__ = 'authors'
    id = Column(Integer, primary_key=True)
    name = Column(String(32))

    def __repr__(self):
        return self.name

#创建链接                数据库类型+要使用的底层sql实现://账号:密码@ip地址/数据库名称                            echo=True会把创建时候的信息打印下来
engine = create_engine('mysql+pymysql://root:qQ1002324991.@1.117.160.157/learn_db', encoding='utf-8')
Base.metadata.create_all(engine) #创建表结构